package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.common.BizException;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.*;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentMapper;

    /**
     * 分页查询学员
     *
     * @param page
     * @return
     */
    @Override
    public PageBean getStudentList(StudentQueryParam page) {
        //开启分页
        PageHelper.startPage(page.getPage(), page.getPageSize());
        List<Student> studentList = studentMapper.selectStusList(page);
        Page<Student> studentPage = (Page<Student>) studentList;
        return new PageBean(studentPage.getTotal(), studentList);
    }

    /**
     * 添加学员
     *
     * @param student
     */
    @Override
    public void insertStudent(Student student) {
        if (student.getClazzId() == null) {
            throw new BizException("班级不能为空");
        }
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());
        studentMapper.insertStudent(student);
    }

    /**
     * 根据id查询学生
     *
     * @param id
     * @return
     */
    @Override
    public Student getStufentById(Integer id) {
        Student student = studentMapper.getStufentById(id);
        return student;
    }

    /**
     * 修改学生信息
     *
     * @param student
     */
    @Override
    public void updateStudent(Student student) {
        student.setUpdateTime(LocalDateTime.now());
        studentMapper.updateStudent(student);
    }

    /**
     * 批量删除学员
     *
     * @param ids
     */
    @Override
    public void deleteStudents(Integer[] ids) {
        studentMapper.deleteStudents(ids);
    }

    /**
     * 违纪处理
     *
     * @param id
     * @param score
     */
    @Override
    public void violationHandle(Integer id, Integer score) {
        studentMapper.updateStudentViolation(id, score);
    }

    /**
     * 根据班级查询人数
     */
    @Override
    public ClazzOption getStudentsByClazz() {
        List<Map<String, Object>> mapList = studentMapper.selectStuNumByClazzId();
        List<Long> dataList = mapList.stream().map(m -> (Long) m.get("total")).collect(Collectors.toList());
        List<String> clazzList = mapList.stream().map(m -> (String) m.get("clazzName")).collect(Collectors.toList());
        return new ClazzOption(clazzList, dataList);
    }

    /**
     * 学员学历统计
     *
     * @return
     */
    @Override
    public List<NameValueData> studentDegreeData() {
        List<NameValueData> list = studentMapper.studentDegreeData();
        return list;
    }
}
